package com.takepoints.mobile;

import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.facebook.android.Facebook.DialogListener;
import com.takepoints.android.TPConst;
import com.takepoints.android.services.SecurityServices;
import com.facebook.android.FacebookVO;
import com.takepoints.android.util.StringUtil;

public class FacebookApps extends BaseActivity {
	
	// http://developers.facebook.com/docs/mobile/android/build/
	// ** http://www.londatiga.net/it/how-to-use-facebook-sdk-to-post-status-from-android/
	
	// http://stackoverflow.com/questions/7785780/post-to-wall-facebook-api
	// http://stackoverflow.com/questions/2953146/android-java-post-simple-text-to-facebook-wall
	// http://stackoverflow.com/questions/4093618/android-facebook-api-post
	
	// http://stackoverflow.com/questions/4388992/key-hash-for-android-facebook-app
	// http://help.appmakr.com/entries/21004006-how-to-add-facebook-authentication-to-your-android-app
	// http://www.integratingstuff.com/2010/10/14/integrating-facebook-into-an-android-application/
	
	// Facebook Permission List
	// http://developers.facebook.com/docs/authentication/permissions/
	// http://developers.facebook.com/docs/reference/api/user/
	// http://developers.facebook.com/docs/mobile/android/sso/
	
	/*
	App ID: 260050780743981
	App Secret: f9ea2f3452c2b1f78b552ff59e39e658
	Android Key Hash : Bmce+9aHdOoVtE7fS3B07tfj7Bc=
	*/
	
	private String fbEvent;
	
	private Facebook mFacebook;
	private CheckBox mFacebookBtn;
	private ProgressDialog mProgress;
	
	private String errorMsg = "No Error";
	
	private static final String[] PERMISSIONS = new String[]{ "publish_stream", "read_stream"
															, "offline_access", "email" };
	public static final String APP_ID = "260050780743981";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
	        .detectDiskReads()
	        .detectDiskWrites()
	        .detectNetwork()   // or .detectAll() for all detectable problems
	        .penaltyLog()
	        .build());
			
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
	        .detectLeakedSqlLiteObjects()
	        .penaltyLog()
	        .penaltyDeath()
	        .build());
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.socialaccount);
        manageMenu(0);
        
        try{
	        Bundle bundle = this.getIntent().getExtras();
	        fbEvent = bundle.getString("FB_EVENT");
        } catch(Exception e){ }
    	
        mFacebookBtn = (CheckBox)findViewById(R.id.chkFacebook);
    	mFacebookBtn.setText("Facebook");
    	
        mProgress = new ProgressDialog(this);
        mFacebook = new Facebook(APP_ID);
        
        SessionStore.restore(mFacebook, this);
        if(mFacebook.isSessionValid()){
        	mFacebookBtn.setChecked(true);
        	String name = SessionStore.getName(this);
        	name = (StringUtil.isEmpty(name))?"Unknown":name;
        	mFacebookBtn.setText(" Facebook (" + name + ")");
        	mFacebookBtn.setTextColor(Color.WHITE);
        }
        
        mFacebookBtn.setOnClickListener(new OnClickListener(){
        	@Override
        	public void onClick(View v) {
        		onFacebookClick();
        	}
        });
    }
	
	private void onFacebookClick(){
		if(mFacebook.isSessionValid()){
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Delete current Facebook connection?").setCancelable(false)
				   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					   public void onClick(DialogInterface dialog, int id) {
						   fbLogout();
					   }
				   })
				   .setNegativeButton("No", new DialogInterface.OnClickListener() {
					   public void onClick(DialogInterface dialog, int id) {
						   dialog.cancel();
						   mFacebookBtn.setChecked(true);
					   }
				   }
			);
			final AlertDialog alert = builder.create();
			alert.show();
		} else {
			mFacebookBtn.setChecked(false);
			mFacebook.authorize(this, PERMISSIONS, -1, new FbLoginDialogListener());
		}
	}
	
	private final class FbLoginDialogListener implements DialogListener {
		public void onComplete(Bundle values){
			SessionStore.save(mFacebook, FacebookApps.this);
			mFacebookBtn.setText(" Facebook (No Name)");
			mFacebookBtn.setChecked(true);
			mFacebookBtn.setTextColor(Color.WHITE);
			getFbInfo();
		}
		
		public void onFacebookError(FacebookError error){
			Toast.makeText(FacebookApps.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
			mFacebookBtn.setChecked(false);
		}
		
		public void onError(DialogError error){
			Toast.makeText(FacebookApps.this, "Facebook connection failed", Toast.LENGTH_SHORT).show();
			mFacebookBtn.setChecked(false);
		}
		
		public void onCancel(){
			mFacebookBtn.setChecked(false);
		}
	}
	
	private void getFbInfo(){
		mProgress.setMessage("Finalizing ...");
		mProgress.show();
		new Thread() {
			@Override
			public void run() {
				FacebookVO fb = new FacebookVO();
				int what = 1;
				String me = null;
				try {
					me = mFacebook.request("me");
					JSONObject jsonObj = (JSONObject) new JSONTokener(me).nextValue();
					fb.setId(jsonObj.getString("id"));
					fb.setName(jsonObj.getString("name"));
					fb.setFirstName(jsonObj.getString("first_name"));
					fb.setLastName(jsonObj.getString("last_name"));
					fb.setEmail(jsonObj.getString("email"));
					fb.setGender(jsonObj.getString("gender"));
					what = 0;
					fb.setBirthday(jsonObj.getString("birthday"));	// MM/DD/YYYY format
				} catch (Exception ex) {
//					errorMsg = ex.getMessage() + " (" + me + ")";
				}
				mFbHandler.sendMessage(mFbHandler.obtainMessage(what, fb));
			}
		}.start();
	}
	
	private void fbLogout() {
		mProgress.setMessage("Disconnecting from Facebook");
		mProgress.show();
		new Thread() {
			@Override
			public void run() {
				SessionStore.clear(FacebookApps.this);
				int what = 1;
				try {
					mFacebook.logout(FacebookApps.this);
					what = 0;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				mHandler.sendMessage(mHandler.obtainMessage(what));
			}
		}.start();
	}
	
	private Handler mFbHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			if (msg.what == 0) {
				String id = "Unknow";
				String name = "No Name";
				String email = "No Email";
				FacebookVO fb = (FacebookVO) msg.obj;
				if(fb != null){
					if(!StringUtil.isEmpty(fb.getId())){
						id = fb.getId();
					}
					if(!StringUtil.isEmpty(fb.getName())){
						name = fb.getName();
					}
					if(!StringUtil.isEmpty(fb.getEmail())){
						email = fb.getEmail();
					}
				}
				SessionStore.saveFbId(id, FacebookApps.this);
				SessionStore.saveName(name, FacebookApps.this);
				SessionStore.saveInfo(fb, FacebookApps.this);
				
				if("LOGIN".equals(fbEvent)){
					String passwd = String.valueOf(new java.util.Date().getTime());
					int mid = SecurityServices.registerUser(email, passwd);
					popup("Member id = " + mid + " (" + email + ")");
					if(mid > 0){
						if(sharePref == null){
							initSharedPreference();
						}
						Editor editor = sharePref.edit();
						editor.putString(TPConst.PRF_USRNAME, email);
						editor.putString(TPConst.PRF_PASSWD, passwd);
						editor.putInt(TPConst.PRF_MEMBER_ID, mid);
						editor.commit();
					}
				}
				
				mFacebookBtn.setText("  Facebook (" + name + ")");
				Toast.makeText(FacebookApps.this, "Connected to Facebook as " + name, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(FacebookApps.this, "Connected to Facebook", Toast.LENGTH_SHORT).show();
			}
//			alert(errorMsg);
		}
	};
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mProgress.dismiss();
			if (msg.what == 1) {
				Toast.makeText(FacebookApps.this, "Facebook logout failed", Toast.LENGTH_SHORT).show();
			} else {
				mFacebookBtn.setChecked(false);
				mFacebookBtn.setText("  Facebook (Not connected)");
				mFacebookBtn.setTextColor(Color.GRAY);
				Toast.makeText(FacebookApps.this, "Disconnected from Facebook", Toast.LENGTH_SHORT).show();
			}
		}
	};
    
}
